import {
  Body,
  Controller,
  Get,
  HttpCode,
  Post,
  Request,
  UseGuards
} from '@nestjs/common'
import { Role } from 'src/users/enums/role.enum'
import { AuthService } from './auth.service'
import { Roles } from './decorators/roles.decorator'
import { LoginDto } from './dto/login.dto'
import { RegisterDto } from './dto/register.dto'
import { JwtAuthGuard } from './guards/jwt-auth.guard'
import { RolesGuard } from './guards/roles.guard'
import { AuthenticatedRequest } from './interfaces/request.interface'

@Controller('api/auth')
export class AuthController {
  constructor(private readonly authService: AuthService) {}

  @Post('login')
  @HttpCode(200)
  async login(@Body() dto: LoginDto) {
    const user = await this.authService.login(dto)
    const accessToken = this.authService.signJwt(user)
    return { accessToken, user }
  }

  @Post('register')
  async register(@Body() dto: RegisterDto) {
    const user = await this.authService.register(dto)
    const accessToken = this.authService.signJwt(user)
    return { accessToken, user }
  }

  @Get('whoami')
  @UseGuards(JwtAuthGuard)
  getCurrentUser(@Request() req: AuthenticatedRequest) {
    return req.user
  }

  @Get('admin')
  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles(Role.ADMIN)
  getAdmin(@Request() req: AuthenticatedRequest) {
    return req.user.roles
  }
}
